package com.drore.cloud.controller.sys;

import com.drore.cloud.constant.LocalConstant;
import com.drore.cloud.domain.Developer;
import com.drore.cloud.domain.sys.RestMessage;
import com.drore.cloud.exception.ApiException;
import com.drore.cloud.exception.UserNotLoginException;
import com.drore.cloud.sdkjdbc.core.JdbcRunner;
import com.drore.cloud.utils.GsonUtil;
import com.drore.cloud.utils.ThreadLocalHolder;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

/***
 * 浙江卓锐科技股份有限公司 版权所有@Copyright 2016
 * 说明
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a>
 * 2017/09/18 16:20
 */
@Api("登录模块")
@Controller
@RequestMapping("/cms/user")
public class LoginController {
    @Autowired
    private JdbcRunner run;
    @Value(value="classpath:default.json")
    private Resource resource;

    @Value(value="classpath:field_type.json")
    private Resource field_type_resource;

    @ApiOperation(value = "登录", notes = "根据用户名密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usercode", value = "用户名", required = true, dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "string"),
    })
    @PostMapping("/login")
    @ResponseBody
    public RestMessage login(@RequestParam(value = "usercode") String usercode, @RequestParam(value = "password") String password, HttpServletRequest request) {
        RestMessage rm = new RestMessage();
        Map<String, Object> sys_user_info = run.queryFirstByRName(/*Developer.class,*/"developer_info", ImmutableMap.<String, Object>of("appid", usercode));
        System.out.println("用户信息"+sys_user_info);
        //数据库找到该用户
        if (sys_user_info.size()>0) {
            String password_right = Objects.toString(sys_user_info.get("appscrect"));
            //暂时不做md5  开发者登录密码  可以明文 无需加密
            if(password.equals(password_right)){
                Map sessionMap = ThreadLocalHolder.getSessionMap();
                sessionMap.put(ThreadLocalHolder.getSessionId(), sys_user_info);
                rm.setData(sys_user_info);
                rm.setSuccess(true);
            }else {
                throw  new ApiException("用户名或密码错误");
            }
        } else {
            throw  new ApiException("用户名或密码错误");
        }
        return rm;
    }

    @ApiOperation(value = "退出", notes = "退出")
    @GetMapping("/signOut")
    @ResponseBody
    public RestMessage signOut() {
        RestMessage rm = new RestMessage();
        ThreadLocalHolder.removeCurrentUser();
        return rm;
    }

    @ApiOperation(value = "获取菜单", notes = "获取菜单")
    @PostMapping("/getMenu")
    @ResponseBody
    public RestMessage getMenu() {
        RestMessage rm = new RestMessage();
        System.out.println(getUserMenu());
        String userMenuJson = getUserMenu();
        Map userMenu = GsonUtil.create().fromJson(userMenuJson, Map.class);
        Map<String, Object> sys_user_info = (Map<String, Object>)ThreadLocalHolder.getCurrentUser();
        if(sys_user_info==null){
            throw new UserNotLoginException();
        }
        String role = Objects.toString(sys_user_info.get("role"));
        Object o = userMenu.get(role);
        rm.setData(o);
        return rm;
    }

    @ApiOperation(value = "获取字段类型", notes = "根据数据库类型 返回相应的 字段类型")
    @PostMapping("/get_field_type")
    @ResponseBody
    public RestMessage getFieldType() {
        RestMessage rm = new RestMessage();
        System.out.println(getUserMenu());
        String field_type_json = getUserFieldType();
        Map field_type = GsonUtil.create().fromJson(field_type_json, Map.class);
        Map<String, Object> sys_user_info = (Map<String, Object>)ThreadLocalHolder.getCurrentUser();
        if(sys_user_info==null){
            throw new UserNotLoginException();
        }
        String data_type = Objects.toString(sys_user_info.get("data_type"));
        Object o = field_type.get(data_type);
        rm.setData(o);
        return rm;
    }

    @ApiOperation(value = "退出登录", notes = "退出登录")
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request) {
        Enumeration<String> sessionAttributes = request.getSession().getAttributeNames();
        while (sessionAttributes.hasMoreElements()) {
            String attr = sessionAttributes.nextElement();
            System.out.println("loginout-->attr:" + attr);
            request.getSession().removeAttribute(attr);
        }
        request.getSession().removeAttribute(LocalConstant.SESSION_CURRENT_USER);
        return "redirect:/Tlogin.html";
    }


    public String getUserMenu()  {
        BufferedReader br = null;
        String result=null;
        try {
            br = new BufferedReader(new InputStreamReader(resource.getInputStream(), Charsets.UTF_8));
            StringBuffer message=new StringBuffer();
            String line = null;
            while((line = br.readLine()) != null) {
                message.append(line);
            }
            String defaultString=message.toString();
            result=defaultString.replace("\r\n", "").replaceAll(" +", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String getUserFieldType()  {
        BufferedReader br = null;
        String result=null;
        try {
            br = new BufferedReader(new InputStreamReader(field_type_resource.getInputStream(), Charsets.UTF_8));
            StringBuffer message=new StringBuffer();
            String line = null;
            while((line = br.readLine()) != null) {
                message.append(line);
            }
            String defaultString=message.toString();
            result=defaultString.replace("\r\n", "").replaceAll(" +", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
